<template>
    <div class="app-container">
        <!--工具条-->
        <el-row style="padding-bottom: 0;">
            <el-col :span="24" class="toolbar">
                <el-form :inline="true" :model="filters" ref="filterForm">
                    <el-form-item label="广告名称" >
                        <el-input v-model="filters.title" ></el-input>
                    </el-form-item>
                    <el-form-item label="广告编码" >
                        <el-input v-model="filters.coding" ></el-input>
                    </el-form-item>
                    <el-form-item label="位置" >
                        <el-select v-model="filters.position"  :clearable="true">
                            <el-option value="0" label="首页"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" >
                        <el-select v-model="filters.status"  :clearable="true">
                            <el-option value="0" label="有效"></el-option>
                            <el-option value="1" label="无效"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="有效时间">
                            <el-date-picker v-model="filters.periods" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                                            :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
                                            range-separator="-" end-placeholder="结束日期"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button  type="primary" v-on:click="handleSearch('filterForm')">搜索</el-button><!-- <v-hasRole="'query'" -->
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24" class="toolbar">
                <el-form :inline="true">
                    <el-form-item>
                        <el-button  type="primary" size="small" @click="handleAdd">新增</el-button><!-- <v-hasRole="'add'" -->
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <!--工具条结束-->
        <!--列表开始-->
        <el-table :data="pagination.records" :height="heightNum" highlight-current-row v-loading="isLoading" border>
            <el-table-column prop="title" label="广告名称" ></el-table-column>
            <el-table-column prop="coding" label="广告编码" ></el-table-column>
            <el-table-column label="展示" >
                <template slot-scope="scope">
                    <el-image style="width: 100px; height: 100px" :src="scope.row.imgUrl"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="size" label="尺寸" ></el-table-column>
            <el-table-column prop="priority" label="优先级" ></el-table-column>
            <el-table-column prop="status" label="状态" ></el-table-column>
            <el-table-column prop="startTime" label="开始时间" ></el-table-column>
            <el-table-column prop="endTime" label="结束时间" ></el-table-column>
            <el-table-column label="操作" min-width="130" >
                <template slot-scope="scope">
                    <el-button  @click="changeStatus(scope.row)" v-if="scope.row.status == 0"  type="primary" size="small">作废</el-button>
                    <el-button  @click="changeStatus(scope.row)" v-if="scope.row.status == 1"  type="primary" size="small">生效</el-button>
                    <el-button  @click="handleEdit(scope.$index, scope.row)" type="primary" size="small">编辑</el-button>
                    <el-button  @click="deleteAdver(scope.row)" type="primary" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表结束-->
        <!--分页开始-->
        <div class="pagination" v-if='pagination.total > 0'>
            <el-pagination layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                           :current-page.sync="pagination.current"
                           @current-change="handleCurrentChange"
                           :page-size="size" :page-sizes="[10, 20, 50, 100]"
                           :total="pagination.total" style="float:right;">
            </el-pagination>
        </div>

        <!--分页结束-->
        <!--新增/修改开始-->
        <section>
            <!--新增|编辑 界面-->
            <el-dialog :title="formObj.title" :visible.sync="formObj.formVisible" :close-on-click-modal="false" >
                <el-form  :model="formObj.formModel" class="demo-form-inline" :rules="rules" :inline="true" v-loading="tabIsLoading"
                         label-width="100px" label-position="right" ref="mailForm">
                    <table style="border-collapse:separate; border-spacing:0px 1px;">
                        <tr>
                            <td>
                                <el-form-item label="广告名称" prop="title">
                                    <el-input v-model="formObj.formModel.title" placeholder="请输入内容" ></el-input>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item label="位置" prop="position">
                                    <el-select v-model="formObj.formModel.position"  :clearable="true">
                                        <el-option value="0" label="首页"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <td>
                                <el-form-item label="尺寸" prop="size">
                                    <el-input v-model="formObj.formModel.size" placeholder="请输入内容" ></el-input>
                                </el-form-item>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <el-form-item label="优先级" prop="priority">
                                    <el-select v-model="formObj.formModel.priority"  :clearable="true">
                                        <el-option value="0" label="0"></el-option>
                                        <el-option value="1" label="1"></el-option>
                                        <el-option value="2" label="2"></el-option>
                                    </el-select>
                                </el-form-item>
                            </td>
                            <td colspan="2">
                                <el-form-item label="有效时间" prop="periods">
                                    <el-date-picker v-model="formObj.formModel.periods" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                                                    :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
                                                    range-separator="-" end-placeholder="结束日期"></el-date-picker>
                                </el-form-item>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <el-form-item label="状态" prop="status">
                                    <el-radio-group v-model="formObj.formModel.status">
                                        <el-radio :label="0">有效</el-radio>
                                        <el-radio :label="1">无效</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </td>
                            <td colspan="2">
                                <el-form-item label="链接地址" prop="imgLinkUrl">
                                    <el-input class="long_input400" v-model="formObj.formModel.imgLinkUrl" placeholder="请输入内容" ></el-input>
                                </el-form-item>
                            </td>
                        </tr>
                        <tr>
                            <td >
                                <el-form-item label="图片地址" class="full-height">
                                    <el-upload class="upload-demo" ref="upload" :on-change="handleChange" action="url"
                                     :on-preview="handlePreview" :on-remove="handleRemove" :http-request="uploadImg" :file-list="fileList" :limit="1" :auto-upload="false">
                                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                                    </el-upload>
                                  <!--  <sd-upload-img ref="uploadImg" uploadUrl="api/returnOrder/updateImg" :pre-file-list="fileList" :multiple="false" :limit-num="1"
                                                   @uploadSuccess="handleUploadImgSuccess" @uploadError="handleUploadImgError" @removeImg="handleRemoveImg">
                                    </sd-upload-img>-->
                                </el-form-item>
                            </td>
                        </tr>
                    </table>
                </el-form>
                <div v-if="formObj.title !== '查看'" slot="footer" class="dialog-footer">
                    <el-button @click.native="handleClose('mailForm')">取消</el-button>
                    <el-button type="primary" @click.native="handleSubmit('mailForm')">提交
                    </el-button>
                </div>
            </el-dialog>
        </section>
        <!--新增/修改结束-->
    </div>
</template>

<script>
    import moment from "moment";
    import http from '../../../axios/http';
    import {isNotEmpty,isEmpty} from "../../../filter";

    export default {
        name: 'floorInfo',
        data() {
            return {
                pickerOption: {
                    shortcuts: this.utils.getDateShortcuts(), // 自定义周期快捷选项
                    onPick: (dateRange => {
                        console.log(dateRange);
                        if(!dateRange.maxDate) {
                            return;
                        }
                        dateRange.maxDate.setHours(23);
                        dateRange.maxDate.setMinutes(59);
                        dateRange.maxDate.setSeconds(59);
                        this.filters.createTime = [dateRange.minDate, dateRange.maxDate];
                    })
                },
                filters:{
                    title:null,
                    coding:null,
                    position:null,
                    status:null,
                    periods:[]
                },
                code:null,
                fileList:[],
                pagination: {
                    total: 0,
                    current: 1,
                    records: []
                },
                heightNum: null,
                size: 20,
                isLoading: false,
                tabIsLoading: false,
                selecteds: [],//列表选中列
                formObj: {
                    title: null,
                    formModel: {
                        title:null,
                        position:null,
                        size:null,
                        priority:null,
                        periods: [],
                        status:0,
                        imgLinkUrl:null,
                    },
                    formVisible: false//编辑界面是否显示
                },
                rules: {
                    file: [
                        { required: true, message: '请上传图片' }
                    ],
                    title: [
                        {required: true, message: '请输入广告名称', trigger: 'blur'},
                    ],
                    position: [
                        {required: true, message: '请选择位置', trigger: 'change'}
                    ],
                    size: [
                        {required: true, message: '请输入尺寸', trigger: 'blur'}
                    ],
                    priority: [
                        {required: true, message: '请选择优先级', trigger: 'change'},
                    ],
                    periods: [
                        {type: "array", required: true, message: '请选择生失效时间', trigger: 'change'}
                    ],
                    status: [
                        {required: true, message: '请选择状态', trigger: 'change'},
                    ],
                    imgLinkUrl: [
                        {required: true, message: '请输入链接地址', trigger: 'blur'},
                    ]
                },
            }
        },
        methods: {
            loadPagination() {
                const self = this;
                window.console.log("this.pagination.page:" + self.pagination.page);
                let params = {
                    page: this.pagination.current === 0 ? 1 : this.pagination.current,
                    size: this.size === 0 ? 20 : this.size
                };
                if(isNotEmpty(this.filters.title)){
                    params['search_like_title'] = this.filters.title;
                }
                if(isNotEmpty(this.filters.coding)){
                    params['search_like_coding'] = this.filters.coding;
                }
                if(isNotEmpty(this.filters.position)){
                    params['search_eq_position'] = this.filters.position;
                }
                if(isNotEmpty(this.filters.status)){
                    params['search_eq_status'] = this.filters.status;
                }
                if(this.filters.periods  && this.filters.periods.length > 1) {
                    let periodStart = moment(this.filters.periods[0]).format("YYYY-MM-DD HH:mm:ss");
                    let periodEnd = moment(this.filters.periods[1]).format("YYYY-MM-DD HH:mm:ss");
                    params['search_ge_startTime'] = periodStart;
                    params['search_le_endTime'] = periodEnd;
                }
                window.console.log("params" + JSON.stringify(params));
                self.isLoading = true;
                http.get("api/advertInfo", {params:params}).then(response => {
                    this.isLoading = false;
                    let current = this.pagination.current;
                    this.pagination = response;
                    this.pagination.current = current;
                });
            },
            handleSearch(ref) {
                this.$refs[ref].validate((valid) => {
                    if (valid) {
                        this.handleCurrentChange(1);
                    }
                });
            },

            //上传图片
            handleRemove(file, fileList) {
                this.fileList = [];
            },
            handlePreview(file) {
                console.log(file);
            },
            handleChange(file, fileList) {
                //  限制单张上传，超过限制即覆盖
                if (fileList.length > 1) {
                    fileList.splice(0, 1);
                }

                //  校验
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                    this.$message.error("上传图片大小不能超过 5MB!");
                    this.handleRemove(file, fileList);  //  不符合要求删除文件
                    return false;
                }

                const isImage = file.raw.type.includes("image");
                if (!isImage) {
                    this.$message.error("上传的格式必须是图片!");
                    this.handleRemove(file, fileList);
                    return false;
                }
            },

           /* //图片
            //上传成功
            handleUploadImgSuccess(response, fileList) {
                if (response.code == 200) {
                    this.formModel.imgUrl = response.imgUrl;
                    this.formModel.imagePath = response.imagePath;
                    this.$message({message: this.$t('current.registerFromProvider.tips.success'),type: 'success'});
                }else{
                    this.$message({message: this.$t('current.registerFromProvider.tips.failure'),type: 'error'});
                    console.error("error:" + JSON.stringify(response.err))
                }
            },*/
          /*  //上传失败
            handleUploadImgError(err) {
            },*/
          /*  //删除图片
            handleRemoveImg(){
                if(this.formModel.imgUrl == '' || this.formModel.imgUrl == undefined){
                    this.$message({message: this.$t('current.registerFromProvider.tips.IDNotFound'),type: 'warning'});
                }else{
                    this.formModel.imgUrl = '';
                    this.formModel.imgUrlPath = '';
                }
            },*/

            handleSubmit(ref) {//提交表单
                console.log("提交表单");
                this.$refs[ref].validate((valid) => {
                    if (valid) {
                        this.$refs.upload.submit();
                    }
                    return;
                });
            },

            uploadImg(file){
                let url = "api/advertInfo";
                let method = "post";
                let param = new FormData();
                //通过append向form对象添加图片数据
                param.append('file',file.file);
                //添加form表单中其他数据
                param.append('title',this.formObj.formModel.title);
                param.append('position',this.formObj.formModel.position);
                param.append('size',this.formObj.formModel.size);
                param.append('priority',this.formObj.formModel.priority);
                param.append('status',this.formObj.formModel.status);
                param.append('imgLinkUrl',this.formObj.formModel.imgLinkUrl);
                if(this.formObj.formModel.periods) {
                    let periodStart = moment(this.formObj.formModel.periods[0]).format("YYYY-MM-DD HH:mm:ss");
                    let periodEnd = moment(this.formObj.formModel.periods[1]).format("YYYY-MM-DD HH:mm:ss");
                    param.append('startTime',periodStart);
                    param.append('endTime',periodEnd);
                }
                this.tabIsLoading = true;
                if (this.formObj.formModel.id) {
                    param.append('id',this.formObj.formModel.id);
                    http.put(url, param).then(response => {
                        if(response.code === 200){
                            this.$message.success(response.msg)
                            this.formObj.formVisible = false
                            this.fileList = [];
                            this.loadPagination();
                        }else {
                            this.$message.warning(response.msg)
                        }
                        this.tabIsLoading = false;
                    })
                    return;
                }
                http.post(url, param).then(response => {
                    if(response.code === 200){
                        this.$message.success(response.msg)
                        this.formObj.formVisible = false
                        this.fileList = [];
                        this.loadPagination();
                    }else {
                        this.$message.warning(response.msg)
                    }
                    this.tabIsLoading = false;
                })
            },

            //生效失效
            changeStatus(row){
              http.get("api/advertInfo/"+row.id).then(respone =>{
                  if(respone.code === 200){
                      this.$message.success(respone.msg);
                      this.loadPagination();
                  }else {
                      this.$message.warning(respone.msg);
                  }
              })
            },

            //删除
            deleteAdver(row){
                this.$confirm('确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    http.delete("api/advertInfo/"+row.id).then(respone =>{
                        if(respone.code === 200){
                            this.$message.success(respone.msg);
                            this.loadPagination();
                        }else {
                            this.$message.warning(respone.msg);
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                })
            },

            handleAdd() {//打开新增界面
                this.isLoading = false;
                this.code = null;
                this.formObj = {
                    title: '新增',
                    formVisible: true,
                    formModel: {
                        title:null,
                        position:null,
                        size:null,
                        priority:null,
                        periods: [],
                        status:0,
                        imgLinkUrl:null,
                    }
                };
            },

            handleEdit(index, row) {//打开编辑界面
                this.isLoading = false;
                this.formObj = {
                    title: '编辑',
                    action: 'update',
                    formVisible: true,
                    formModel: Object.assign({}, row)
                };
                let time = [];
                time[0] = row.startTime;
                time[1] = row.endTime;
                this.formObj.formModel.periods = time
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.size = val;
                this.loadPagination();
            },
            handleCurrentChange(val) {
                window.console.log('this.pagination.page:' + val);
                this.pagination.current = val;
                window.console.log('排序动作:' + this.sort);
                this.loadPagination();
            },
            handleClose(ref) {//关闭表单
                this.formObj.formVisible = false;
                this.$refs[ref].resetFields();
                //this.handleReset(ref);
            },
            // 计算table高度
            initData() {
                let self = this;
                // 2.0版本特殊处理
                setTimeout(function () {
                    self.heightNum = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 200 + "px";
                },10);
                // 响应窗口大小改变
                window.onresize = function () {
                    self.heightNum = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 200 + "px";
                };
            },
        },
        mounted() {
            this.initData();
            this.loadPagination();
        },
    }
</script>

